/*
Source : https://leetcode.com/problems/combination-sum/
Author : nflush@outlook.com
Date   : 2016-07-26
*/

/*
39. Combination Sum

    Total Accepted: 102269
    Total Submissions: 316041
    Difficulty: Medium

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

    All numbers (including target) will be positive integers.
    The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

Subscribe to see which companies asked this question
*/

class Solution {
private:
    void helper(vector<int> &candidates, int start, int target, vector<int> &solution, vector< vector<int> > &result) {
        if (target<0){
            return;
        }
        if (target==0){
            result.push_back(solution);
            return;
        }
        for(int i=start; i<candidates.size() && target >= candidates[i]; i++){
            //skip duplicates
//            if (i>start && candidates[i] == candidates[i-1]) {
//                continue;
//            }
//            if (target < candidates[i]) return;
            solution.push_back(candidates[i]);
            helper(candidates, i, target - candidates[i], solution, result);
            solution.pop_back();
        }
    }
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector< vector<int> > result;
        if (candidates.size()<=0){
            return result;
        }
        sort(candidates.begin(), candidates.end());
        
        vector<int> solution;
        helper(candidates, 0, target, solution, result);

        return result;
    }
};

